<template>
  <div>
    <a-form layout="horizontal" :rules="formRules" :model="formData" @finish="handleSubmit">
      <a-form-item
        style="display: flex; align-items: center; justify-content: center; align-content: center"
      >
        <div style="font-size: 28px; text-align: center">新用户注册</div>
      </a-form-item>
      <a-form-item required hasFeedback name="username">
        <a-input v-model:value="formData.username" size="large" placeholder="请输入用户名">
          <template #prefix
            ><user-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input>
      </a-form-item>
      <a-form-item required hasFeedback name="mobile">
        <a-input v-model:value="formData.mobile" size="large" placeholder="请输入手机号">
          <template #prefix
            ><mobile-outlined type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input>
      </a-form-item>
      <div id="captcha" style="width: 450px; max-height: 40px; margin-bottom: 22px"></div>
      <a-form-item has-feedback required name="captcha">
        <a-input-group compact>
          <a-input
            v-model:value="formData.captcha"
            size="large"
            type="text"
            placeholder="验证码"
            style="width: calc(100% - 115px)"
          >
            <template #prefix>
              <mail-outlined type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input>
          <a-button
            class="getCaptcha"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            size="large"
            style="width: 112px; margin-left: 3px"
            @click="getCaptcha"
            >{{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}</a-button
          >
        </a-input-group>
      </a-form-item>
      <a-form-item required hasFeedback name="password">
        <a-input-password
          v-model:value="formData.password"
          size="large"
          type="password"
          placeholder="请输入密码"
        >
          <template #prefix
            ><lock-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input-password>
      </a-form-item>
      <a-form-item name="invite_code">
        <a-input v-model:value="formData.invite_code" size="large" placeholder="(可选)邀请码">
          <template #prefix
            ><lock-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
          /></template>
        </a-input>
      </a-form-item>
      <a-form-item
        style="
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
        "
      >
        <a-button
          type="primary"
          html-type="submit"
          size="large"
          :loading="loading"
          style="width: 60%"
        >
          立即注册
        </a-button>
        <router-link style="float: right; line-height: 40px" :to="{ name: 'login' }"
          >账号密码登录</router-link
        >
      </a-form-item>
    </a-form>
    <div
      style="
        display: flex;
        align-items: center;
        align-content: center;
        justify-content: center;
        margin-top: 30px;
      "
    >
      <a-button type="link" danger @click="clickFeedback"
        >注册不了？我要反馈(采纳可获赠1个月会员时长)</a-button
      >
    </div>
    <a-modal
      v-model:open="feedShow"
      title="我要反馈"
      style="width: 700px; height: 1000px"
      :footer="null"
    >
      <iframe
        :src="feedbackUrl"
        frameborder="no"
        border="0"
        marginwidth="0"
        marginheight="0"
        scrolling="no"
        allowtransparency="true"
        style="width: 100%; height: 1000px"
      ></iframe>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted } from 'vue'
import { message, InputGroup } from 'ant-design-vue'
import { UserOutlined, LockOutlined, MobileOutlined, MailOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { getSmsCaptcha, doRegister } from '@/api/system/user'
import { getLoginParam } from '@/api/common'
import { validatePhone, validatePassword, validateUserName } from '@/utils/validate'

import { SvgIcon } from '@/components/svg-icon'

export default defineComponent({
  name: 'Register',
  components: {
    UserOutlined,
    LockOutlined,
    SvgIcon,
    MobileOutlined,
    MailOutlined,
    [InputGroup.name]: InputGroup
  },
  setup() {
    const state = reactive<any>({
      loading: false,
      feedShow: false,
      feedbackUrl: 'https://plus.21ds.cn/feedback/index.html?id=FSI4894117794504276',
      setting: {},
      formData: {
        username: '',
        mobile: '',
        authenticate: '',
        invite_code: '',
        token: '',
        password: '',
        captcha: ''
      },
      state: {
        smsSendBtn: false,
        time: 60
      }
    })

    function clickFeedback() {
      state.feedbackUrl = 'https://plus.21ds.cn/feedback/index.html?id=FSI4894117794504276'
      state.feedShow = true
    }

    const router = useRouter()

    onMounted(() => {
      getSetting()
      setTimeout(function () {
        ;(window as any).captchaInit('4960354834839720')
      }, 100)
      if (
        router.currentRoute.value.query.iv_code != undefined &&
        router.currentRoute.value.query.iv_code.length > 0
      ) {
        state.formData.invite_code = router.currentRoute.value.query.iv_code
      }
    })

    const getSetting = () => {
      getLoginParam({})
        .then((res) => {
          console.log(res)
          state.setting = res
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const formRules = {
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: ['blur', 'change']
        },
        {
          validator: validateUserName,
          trigger: ['blur', 'change']
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePassword,
          trigger: ['blur', 'change']
        }
      ],
      mobile: [
        {
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        },
        {
          required: true,
          validator: validatePhone,
          trigger: 'change'
        }
      ],
      captcha: [
        {
          required: true,
          message: '请输入验证码',
          trigger: ['blur', 'change']
        }
      ]
    }

    const initCaptcha = () => {
      ;(window as any).showCaptcha('4960354834839720', '#captcha').then(function (res) {
        state.formData.token = res
        getCaptcha()
      })
    }

    function handleSubmit() {
      state.loading = true
      doRegister(state.formData)
        .then((res) => {
          if (res.code == 200) {
            requestSuccess(null, '注册成功')
            router.push({ name: 'login' })
          } else {
            requestFailed(res)
          }
        })
        .catch((err) => {
          requestFailed(err)
        })
        .finally(() => {
          state.loading = false
          message.destroy()
        })
    }
    let interval = window.setInterval(() => {})
    function getCaptcha() {
      if (state.state.smsSendBtn == true) {
        return false
      }
      if (!state.formData.mobile) {
        requestFailed(null, '请输入手机号')
        return false
      }
      if (state.formData.token == '') {
        initCaptcha()
        return false
      }
      state.state.smsSendBtn = true
      interval = window.setInterval(() => {
        if (state.state.time-- <= 0) {
          state.state.time = 60
          state.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)
      let hide = message.loading('验证码发送中..', 0)
      getSmsCaptcha({
        phone: state.formData.mobile,
        authenticate: state.formData.authenticate,
        token: state.formData.token,
        type: 'register'
      })
        .then((res) => {
          setTimeout(hide, 1000)
          if (res.code === 200) {
            requestSuccess(null, '验证码获取成功')
          } else {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.state.time = 60
            state.state.smsSendBtn = false
            requestFailed(res)
          }
        })
        .catch((err) => {
          setTimeout(hide, 1)
          clearInterval(interval)
          state.state.time = 60
          state.state.smsSendBtn = false
          requestFailed(err)
        })
    }
    return {
      ...toRefs(state),
      handleSubmit,
      clickFeedback,
      interval,
      formRules,
      getCaptcha
    }
  }
})
</script>

<style lang="scss" scoped></style>
